<!--
*@Author: QWP
*@Description: 通讯录
*@Date: 2024-07-08 09:51:28
-->
<template>
  <a-layout class="f-h-100 s-bg-white" id="test">
    <u-collapsed-sider width="250" class="f-padding-l8">
      <u-tree v-model:selectedKeys="state.selectedKeys" 
        title="部门名称" 
        :showSearch="false" 
        :tree-data="tSiderData"
        :fieldNames="{ title: 'name', key: 'keyid' }"
        @select="treeSelect">
      </u-tree>
    </u-collapsed-sider>
    <a-layout class="s-bg-white f-h-100">
      <u-table-header>
        <u-form :model="searchF" :gutter="16" :elements="searchEl" class="f-w-auto"
          :isSearch="true"
          @formChange="getSearch(1)">
          <a-col>
            <a-space>
              <u-icon-button @click="getSearch(1)">查询</u-icon-button>
              <!-- <u-icon-button itype="export">导出</u-icon-button> -->
              <!-- <u-icon-button itype="sms" @click="showSms = true">发送短信</u-icon-button> -->
              <!-- <u-icon-button itype="chat" @click="showChat = true">站内群聊</u-icon-button> -->
            </a-space>
          </a-col>
          <a-col flex="1">
            <a-row justify="end">
              <a-space>
                <u-icon-button itype="add" @click="showEdit = true">新增</u-icon-button>
                <u-icon-button itype="edit" @click="toEdit">修改</u-icon-button>
                <u-icon-button itype="delete" @click="toDel">删除 </u-icon-button>
              </a-space>
            </a-row>
          </a-col>
        </u-form>
      </u-table-header>
      <u-table-content>
        <u-table :columns="columns" 
          :data="tabData" 
          :loading="loading" 
          :scroll="{ y: tabH }"
          v-model:pagination="pagenation" 
          @onSelect="({ selectedRows }) => tabSelData = selectedRows"
          @change="(page) => (pagenation = page, getSearch())">
        </u-table>
      </u-table-content>
    </a-layout>
  </a-layout>

  <!-- 编辑弹窗 -->
  <Edit v-model:open="showEdit" 
    width="40%" 
    wrap-class-name="full-modal" 
    :title="dialogTitle" 
    :id="currentKey"
    @success="showEdit = false; getSearch()" 
    @close="currentKey = ''" />

  <!-- 展示群聊弹窗 -->
  <ChatDialog v-model:open="showChat" 
    width="60%" 
    @close="showChat = false" />

  <!-- 快速短信 -->
  <FastSMS v-model:open="showSms" 
    width="60%" 
    :showSider="false" 
    title="发送短信"
    @close="showSms = false" />

</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch } from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave } from "vue-router";
import { _IFormEl } from "@/components/common/form/interface";
import { ColProps, FormItemProps, TableColumnProps, } from "ant-design-vue";
import { CheckCircleOutlined, ExclamationCircleOutlined, FormOutlined } from '@ant-design/icons-vue';
import { numberC, nullC, alertC, messageC } from '@/util/common'
import { formatAmt, } from '@/util/format.ts'
import dayjs from "dayjs";
import Edit from './Edit.vue'
import { cloneDeep } from 'lodash'
import { usePageSearch } from '@/hooks/usePage'
import UIconFont from '@/components/common/iconfont/IconFont.vue'
import ChatDialog from '@/views/oa/emergency/group/chat/ChatDialog.vue'
import FastSMS from '@/views/oa/assist/sms/fastSms/Index.vue'
import * as linkApi from '@/service/personal/link_book'
import * as unitApi from '@/service/system/unit'
import * as deptApi from '@/service/system/dept'
import { useLoginStore, useBaseStore } from '@/store'
import { storeToRefs } from "pinia";
import { useTableScroll } from "@/hooks/useTable";
const tabH = useTableScroll({ headerHeight: 69 })

const route = useRoute();
const router = useRouter();
const { userInfo } = storeToRefs(useLoginStore())
const { DUTY_TYPE, RELATIONSHIP_TYPE, deptData } = storeToRefs(useBaseStore())

const state = reactive({
  selectedKeys: [],
})

const tSiderData = computed(() => {
  return [
    {
      name: '组织架构',
      keyid: '0-0',
      children: cloneDeep(deptData.value).map(item => {
        item.children = [];
        return item
      })
    },
    {
      name: '我的下属',
      keyid: '1-0',
    },
  ]
})

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 20,
  showTotal: total => `共 ${total} 条`
})
const searchF = reactive({
  model: {},
});
const formItemProps: FormItemProps = {
  labelWidth: '60px',
  wrapperCol: { span: 24 },
};
const searchEl: Array<_IFormEl> = [
  {
    label: "关键字", key: "keyWords", element: "input", col: { span: 6 },
    formItemProps: formItemProps,
    componentProps: {
      placeholder: '部门、单位、姓名、电话'
    }
  },
];

// 列表
const loading = ref<boolean>(false);
const tabData = ref<any[]>([]);
const tabSelData = ref<any[]>();
let columns: Array<TableColumnProps> = reactive([
  {
    dataIndex: "index", title: "序号", width: 50, align: 'center',
    customRender: ({ index }) => index += 1
  },
  { dataIndex: "fkunitname", title: "所属单位", width: 150 },
  { dataIndex: "fkdeptname", title: "所属部门", width: 150 },
  { dataIndex: "fkusername", title: "人员名称", width: 150 },
  {
    dataIndex: "duty", title: "职务", width: 150, align: 'center',
    // customRender: ({ text, record }) => {
    //   let t = DUTY_TYPE.value.find(o => o.value == text) || {};
    //   return nullC(t['label'])
    // }
  },
  { dataIndex: "phone", title: "联系电话", width: 150, align: 'center', },
  { dataIndex: "fkemerusername", title: "紧急联系人", width: 150, align: 'center', },
  { dataIndex: "emerphone", title: "紧急联系电话", width: 150, align: 'center', },
  {
    dataIndex: "relationship", title: "紧急联系人关系", width: 150, align: 'center',
    customRender: ({ text, record }) => {
      let t = RELATIONSHIP_TYPE.value.find(o => o.value == text) || {};
      return nullC(t['label'])
    }
  },
  { dataIndex: "dutyStatus", title: "在岗情况", width: 150, align: 'center', },
  { dataIndex: "remark", title: "备注", width: 200 },
  // { dataIndex: "do", title: "沟通", width: 100, align: 'center', fixed: 'right',
  //   customRender: ({ text, record }) => {
  //     return h(UIconFont, { 
  //       type: 'icon-zaixiangoutong', 
  //       style: { color: '#1890ff' },
  //       onClick: () => {
  //       }
  //     })
  //   }
  // },
]);
let selectedRowKeys = ref<string | number>([])
const rowSelection = ref({
  onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
    tabSelData.value = selectedRows
  },
  onSelectAll: (selected: boolean, selectedRows: DataItem[], changeRows: DataItem[]) => {
    tabSelData.value = selectedRows
  },
});

// 编辑
let dialogTitle = ref<string>("通讯录编辑")
let showEdit = ref<boolean>(false)
let currentKey = ref<string>('')

// 群聊，短信
let showChat = ref<boolean>(false)
let showSms = ref<boolean>(false)

onMounted(() => {
  getSearch()
})

// 列表查询
const getSearch = async (index?: number) => {
  try {
    loading.value = true;
    if (index == 1) {
      pagenation.current = 1
    }
    searchF.model.keywords = searchF.keyWords
    searchF.size = pagenation.pageSize
    searchF.current = pagenation.current
    const res = await linkApi.page(searchF)
    if (res.code == 0) {
      tabData.value = res.data.records || []
      pagenation.total = res.data.total
    }
  } catch (error) { }
  loading.value = false
}

// 我的下属
const getlevelUser = async (index?: number) => {
  try {
    loading.value = true;
    if (index == 1) {
      pagenation.current = 1
    }
    searchF.model.keywords = searchF.keyWords
    searchF.size = pagenation.pageSize
    searchF.current = pagenation.current
    const res = await linkApi.querySubordinate(searchF)
    if (res.code == 0) {
      tabData.value = res.data.records || []
      pagenation.total = res.data.total
    }
  } catch (error) { }
  loading.value = false
}

// 部门树形点击
const treeSelect = (selectedKeys, e) => {
  if(selectedKeys[0] == '1-0') {
    searchF.model.fkdeptid = '';
    getlevelUser(1)
    return
  }

  searchF.model.fkdeptid = selectedKeys[0] == '0-0' ? '' : selectedKeys[0];
  getSearch(1)
}

// 修改
const toEdit = () => {
  if (tabSelData.value.length != 1) {
    alertC("请选择一条数据进行编辑!")
    return
  }
  currentKey.value = tabSelData.value[0]['keyid']
  showEdit.value = true;
}

// 删除
const toDel = () => {
  if (tabSelData.value.length == 0) {
    alertC("请选择需要删除的数据!")
    return
  }
  alertC("确认删除?", "confirm").then(async () => {
    loading.value = true;
    try {
      let ids = tabSelData.value.map(o => o.keyid)
      const res = await linkApi.del({ ids: ids.join() });
      if (res.code == 0) {
        messageC(res.msg, "success");
        getSearch()
      }
      else {
        messageC(res.msg, "error");
      }
    } catch (error) { }
    loading.value = false;
  })
}


</script>

<style lang="scss" scoped>
.icons-list :deep(.anticon) {
  margin-right: 6px;
  font-size: 24px;
}
</style>
